package net.hn.hnms.biz.plan.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import net.hn.hnms.biz.plan.domain.CoalWeekCount;

import net.hn.hnms.biz.plan.domain.PlanDrivage;
import net.hn.hnms.biz.plan.domain.PlanOutput;
import net.hn.hnms.biz.plan.mapper.CoalWeekCountMapper;
import net.hn.hnms.biz.plan.mapper.ExecutionFootageOutputMapper;
import net.hn.hnms.biz.plan.mapper.PlanDrivageMapper;
import net.hn.hnms.biz.plan.mapper.PlanOutputMapper;
import net.hn.hnms.biz.plan.request.BaseReq;

import net.hn.hnms.biz.plan.request.ExecutionFootageOutputReq;
import net.hn.hnms.biz.plan.request.PlanDrivageReq;
import net.hn.hnms.biz.plan.request.PlanOutputReq;
import net.hn.hnms.biz.plan.service.CoalWeekCountService;

import net.hn.hnms.biz.plan.service.IPlanDrivageService;
import net.hn.hnms.biz.plan.service.IPlanOutputService;
import net.hn.hnms.biz.plan.vo.ExecutionFootageOutputVO;
import net.hn.hnms.biz.plan.vo.PlanDrivageVO;
import net.hn.hnms.biz.plan.vo.PlanOutputVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * @author jingantech
 * @description 针对表【coal_week_count】的数据库操作Service实现
 * @createDate 2023-02-01 14:15:12
 */
@Service
public class CoalWeekCountServiceImpl extends ServiceImpl<CoalWeekCountMapper, CoalWeekCount>
        implements CoalWeekCountService {
    @Autowired
    private PlanDrivageMapper planDrivageMapper;
    @Resource
    private PlanOutputMapper planOutputMapper;

    @Autowired
    private IPlanOutputService outputPlanService;
    @Autowired
    private IPlanDrivageService planDrivageService;

    @Autowired
    private ExecutionFootageOutputServiceImpl executionFootageOutputService;


    @Resource
    private ExecutionFootageOutputMapper executionFootageOutputMapper;


    @Override
    public List<CoalWeekCount> selectList(BaseReq baseReq) {
        QueryWrapper<CoalWeekCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "1").orderByDesc("sun_date");
        queryWrapper.ge(baseReq.getBeginDate() != null, "sun_date", baseReq.getBeginDate()).le(baseReq.getBeginDate() != null, "mon_date", baseReq.getEndDate());
        List<CoalWeekCount> list = this.list(queryWrapper);

        return list;
    }

    @Override
    public void calculatedWeeklyOutput(String mineCode,String companyCode) {

        Date date = new Date();
        int whichDay = date.getDay();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化一下
        Calendar calendar1 = Calendar.getInstance();//获取对日期操作的类对象
        Calendar calendar2 = Calendar.getInstance();//获取对日期操作的类对象
        Calendar calendar3 = Calendar.getInstance();//获取上周日时间
        Calendar calendar4 = Calendar.getInstance();//获取上周一时间


        calendar1.add(Calendar.DATE, -(whichDay - 1));
        Date montoday = calendar1.getTime();
        calendar2.add(Calendar.DATE, +(7 - whichDay));
        Date suntoday = calendar2.getTime();
        calendar3.add(Calendar.DATE, -(whichDay));
        Date lastsuntoday = calendar3.getTime();
        calendar4.add(Calendar.DATE, -(whichDay + 7));
        Date lastmontoday = calendar3.getTime();

        int dayDate = dateDay(date);
        //PlanOutput planOutput = null;
        BigDecimal montddivide = null;

        LocalDate localDate = LocalDate.now();
        //当月最后一天
        LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth());
        //当月第一天
        LocalDate firstDay = localDate.with(TemporalAdjusters.firstDayOfMonth());

        WeekFields weekFields = WeekFields.ISO;
        LocalDate now = LocalDate.now();
        LocalDate mondayDate = now.with(weekFields.dayOfWeek(), 1L);//本周第一天
        LocalDate sundayDate = now.with(weekFields.dayOfWeek(), 7L);//本周最后一天
        QueryWrapper<CoalWeekCount> coalWeekCountQueryWrapper = new QueryWrapper<>();
        coalWeekCountQueryWrapper.eq("mon_date", mondayDate).eq("sun_date", sundayDate).eq("type", "1");
        if (mineCode != null){
            coalWeekCountQueryWrapper.eq("mine_code",mineCode);
        }if (mineCode == null){
            coalWeekCountQueryWrapper.isNull("mine_code");
        }
        CoalWeekCount one = this.getOne(coalWeekCountQueryWrapper);
        if (one == null) {

        }
        //上周一和周日
        LocalDate todayOfLastWeek = now.minusDays(7);
        LocalDate lastmonday = todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1);
        LocalDate lastsunday = todayOfLastWeek.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(1);

        boolean before = mondayDate.isBefore(firstDay);//本周第一天如果是本月第一天之前
        if (before) {
            //获取上个月的最后一天
            LocalDate lastMonthdate = LocalDate.now();
            lastMonthdate = lastMonthdate.minusMonths(1);
            LocalDate with = lastMonthdate.with(TemporalAdjusters.lastDayOfMonth());

            Period period = Period.between(mondayDate, with);
            int days = period.getDays() + 1;//相差多少天

            LocalDate lastDay1 = lastMonthdate.with(TemporalAdjusters.lastDayOfMonth());

            //当月第一天
            LocalDate firstDay1 = lastMonthdate.with(TemporalAdjusters.firstDayOfMonth());

            //在计算本月本周有多少天
            Period period1 = Period.between(firstDay, sundayDate);
            int days1 = period1.getDays() + 1;//相差多少天

            //查询上月的总计划/天数*本周上月所占天数+（本月总计划/本月天数*本周本月天数）
            String lastMonth = getLastMonth();
            QueryWrapper<PlanOutput> queryWrapper = new QueryWrapper();
            queryWrapper.eq("output_plan_name", "月计划" + lastMonth);
            queryWrapper.eq(companyCode != null,"company_code",companyCode);
            if (mineCode != null){
                queryWrapper.eq("mine_code",mineCode);
            }
            if (companyCode !=null){
                queryWrapper.eq("company_code",companyCode);
            }
            List<PlanOutput> planOutputs = planOutputMapper.selectList(queryWrapper);

            BigDecimal planOutput1 = new BigDecimal(0);
            if (planOutputs == null ) {
                for (PlanOutput planOutput : planOutputs) {
                    if (planOutput.getPlanOutput() == null){
                        planOutput1 = BigDecimal.ZERO;
                    }
                    planOutput1 = planOutput.getPlanOutput();
                }

            }


            BigDecimal monthcoalOutput = getMonthcoalOutput(mineCode,companyCode);
            BigDecimal monthcoalmultiply = monthcoalOutput.divide(BigDecimal.valueOf(dayDate), 2, BigDecimal.ROUND_UP).multiply(BigDecimal.valueOf(days));
            BigDecimal monthcoalmultiply2 = planOutput1.divide(BigDecimal.valueOf(dayDate), 2, BigDecimal.ROUND_UP).multiply(BigDecimal.valueOf(days1));
            montddivide = monthcoalmultiply.add(monthcoalmultiply2);
        } else {
            //本月总计划/本月天数*本周本月天数=本周计划
            //本周推进度=本周第一天到本周最后一天累计回采长度
            //累计回采长度是这个工作面总共回采的长度
            //剩余长度= 这个工作面总长度-累计回采长度
            BigDecimal monthcoalOutput = getMonthcoalOutput(mineCode,companyCode);
            montddivide = monthcoalOutput.divide(BigDecimal.valueOf(dayDate), 2, BigDecimal.ROUND_UP).multiply(BigDecimal.valueOf(7));
        }


        //获取年计划产量

        PlanOutputReq planOutputReq = new PlanOutputReq();
        int year1 = calendar1.get(Calendar.YEAR);
        planOutputReq.setOutputPlanName(String.valueOf(year1));
        if (mineCode !=null){
            planOutputReq.setMineCode(mineCode);
        }
        if (companyCode!=null){
            planOutputReq.setCompanyCode(companyCode);
        }
        BigDecimal yearCoaloutputMethod = getYearCoaloutputMethod(planOutputReq);

        ExecutionFootageOutputReq finshexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        List<String> strings = new ArrayList<>();
        strings.add(year1 + "-01-01");
        strings.add(year1 + "-12-31");

        finshexecutionFootageOutputReq.setDateTimeRange(strings);
        if (mineCode != null) {
            finshexecutionFootageOutputReq.setMineCode(mineCode);
        }
        //获取年实际完成
        BigDecimal finshCoaloutput = countYearFinshCoaloutput(finshexecutionFootageOutputReq);

        //本周完成量
        //BigDecimal cont = getWeekBigDecimal(montoday, suntoday);
        List<String> thisWeek = new ArrayList<>();
        thisWeek.add(String.valueOf(mondayDate));
        thisWeek.add(String.valueOf(sundayDate));
        ExecutionFootageOutputReq coutexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        coutexecutionFootageOutputReq.setDateTimeRange(thisWeek);
        if (mineCode != null){
        coutexecutionFootageOutputReq.setMineCode(mineCode);}
        BigDecimal cont = countYearFinshCoaloutput(coutexecutionFootageOutputReq);
        //上周完成量
        //BigDecimal lastcont = getWeekBigDecimal(lastmontoday, lastsuntoday);
        List<String> lastWeek = new ArrayList<>();
        lastWeek.add(String.valueOf(lastmonday));
        lastWeek.add(String.valueOf(lastsunday));
        ExecutionFootageOutputReq lastcoutexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        lastcoutexecutionFootageOutputReq.setDateTimeRange(lastWeek);
        if (mineCode !=null){
        lastcoutexecutionFootageOutputReq.setMineCode(mineCode);}
        BigDecimal lastcont = countYearFinshCoaloutput(lastcoutexecutionFootageOutputReq);


        CoalWeekCount coalWeekCount = new CoalWeekCount();
        coalWeekCount.setMonDate(montoday);
        coalWeekCount.setSunDate(suntoday);
        //r日均
        BigDecimal divide1 = cont.divide(BigDecimal.valueOf(7), 2, BigDecimal.ROUND_UP);
        coalWeekCount.setDaily(divide1.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        //weekcoalOutput 本周完成量
        coalWeekCount.setLastWeekCoaloutput(cont.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        BigDecimal decimalsetYearOutputRate = new BigDecimal(0);
        if (yearCoaloutputMethod.compareTo(BigDecimal.ZERO)==0 ) {
            decimalsetYearOutputRate = BigDecimal.valueOf(0);
            coalWeekCount.setYearOutputRate("--");
        }


        if (yearCoaloutputMethod.compareTo(BigDecimal.ZERO)!=0 ) {
            decimalsetYearOutputRate = (finshCoaloutput.subtract(yearCoaloutputMethod)).divide(yearCoaloutputMethod, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            //年完成百分比
            coalWeekCount.setYearOutputRate(decimalsetYearOutputRate + "%");

        }
        //本年完成
        coalWeekCount.setYearFinshCoaloutput(finshCoaloutput.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        //年度计划
        coalWeekCount.setYearCoalOutput(yearCoaloutputMethod.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        BigDecimal subtract = cont.subtract(lastcont.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        if (one != null) {
            coalWeekCount.setId(one.getId());
        }

        if (lastcont != null && lastcont.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal weekdecimalsetYearOutputRate = (cont.subtract(lastcont)).divide(lastcont, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            //周环比率
            coalWeekCount.setWeekOutputrate(weekdecimalsetYearOutputRate + "%");
        }
        if (lastcont == null || lastcont.compareTo(BigDecimal.ZERO)==0) {
            //周环比率
            coalWeekCount.setWeekOutputrate("--");
        }

        //周环比量
        coalWeekCount.setWeekOutputConteRast(subtract.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        //上周工作量
        coalWeekCount.setLastWeekCoaloutput(lastcont.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        // 本周完成量
        coalWeekCount.setWeekcoalOutput(cont.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        //本周计划量
        coalWeekCount.setWeekplanOutput(montddivide.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        int lastyear = year1 - 1;

        List<String> lsatyearthisWeek = new ArrayList<>();
        lsatyearthisWeek.add(String.valueOf(mondayDate.minusYears(1)));
        lsatyearthisWeek.add(String.valueOf(sundayDate.minusYears(1)));
        ExecutionFootageOutputReq lastyearcoutexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        lastyearcoutexecutionFootageOutputReq.setDateTimeRange(lsatyearthisWeek);
        if(mineCode !=null) {
            lastyearcoutexecutionFootageOutputReq.setMineCode(mineCode);
        }
        BigDecimal lastyearcont = countYearFinshCoaloutput(lastyearcoutexecutionFootageOutputReq);


        BigDecimal onYear = cont.subtract(lastyearcont);


        //同比量
        coalWeekCount.setOnYear(onYear);
        if (lastyearcont != null && lastyearcont.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal onYearRate = (cont.divide(lastyearcont, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
            //同比率
            coalWeekCount.setOnYearRate(onYearRate + "%");
        }
        if ( lastyearcont.compareTo(BigDecimal.ZERO)==0){
            coalWeekCount.setOnYearRate("--");
        }
        //超欠
        BigDecimal backRreak = cont.subtract(montddivide);
        coalWeekCount.setBackBreak(backRreak.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        if (montddivide.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal backBrakRate = backRreak.divide(montddivide, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            //超欠百分比
            coalWeekCount.setBackBreakRate(backBrakRate + "%");
        }
        if (montddivide == null || montddivide.compareTo(BigDecimal.ZERO)==0){
            //超欠百分比
            coalWeekCount.setBackBreakRate("--");
        }

        //进度计划

        coalWeekCount.setScheduledPlan(finshCoaloutput.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        coalWeekCount.setLastYearCoaloutput(lastyearcont.divide(new BigDecimal(10000), 2, RoundingMode.HALF_UP));
        coalWeekCount.setType("1");
        coalWeekCount.setMineCode(mineCode);

        // int insert = coalWeekCountMapper.insert(coalWeekCount);
        //System.out.println(insert);
        System.out.println(coalWeekCount);
        boolean b = this.saveOrUpdate(coalWeekCount);
    }

    /**
     * 计算年产量
     *
     * @param executionFootageOutput
     * @return
     */
    private BigDecimal countYearFinshCoaloutput(ExecutionFootageOutputReq executionFootageOutput) {
        BigDecimal bigDecimal = new BigDecimal(0);
        List<ExecutionFootageOutputVO> executionFootageOutputVOS = executionFootageOutputService.selectList(executionFootageOutput);


        if (executionFootageOutputVOS == null) {
            return BigDecimal.ZERO;
        }
        BigDecimal output = BigDecimal.ZERO;
        for (ExecutionFootageOutputVO executionFootageOutputVO : executionFootageOutputVOS) {

            if (executionFootageOutputVO.getOutput() == null) {
                executionFootageOutputVO.setOutput(BigDecimal.ZERO);
            }
            output = output.add(executionFootageOutputVO.getOutput());

        }
        if (output == null) {
            return BigDecimal.ZERO;
        }
        return output;
    }


    /**
     * 计算年计划产量产量
     *
     * @param planOutput
     * @return
     */
    private BigDecimal getYearCoaloutputMethod(PlanOutputReq planOutput) {
        if (planOutput == null) {
            BigDecimal bigDecimal = BigDecimal.ZERO;
            return bigDecimal;
        }
        BigDecimal planOutput1 = BigDecimal.ZERO;
        List<PlanOutputVO> planOutputVOS = outputPlanService.selectList(planOutput);
        if (planOutputVOS == null) {
            BigDecimal bigDecimal = BigDecimal.ZERO;
            return bigDecimal;
        }
        for (PlanOutputVO planOutputVO : planOutputVOS) {
            System.out.println(planOutputVO.getPlanOutput());
            planOutput1 = planOutput1.add(planOutputVO.getPlanOutput());
        }
        return planOutput1;
    }

    /**
     * 计算年计划米数
     *
     * @param planOutput
     * @return
     */
    private BigDecimal getYearFootageMethod(PlanDrivageReq planOutput) {
        if (planOutput == null) {
            BigDecimal bigDecimal = BigDecimal.ZERO;
            return bigDecimal;
        }
        BigDecimal planOutput1 = BigDecimal.ZERO;
        List<PlanDrivageVO> planDrivageVOS = planDrivageService.selectList(planOutput);
        if (planDrivageVOS == null) {
            BigDecimal bigDecimal = BigDecimal.ZERO;
            return bigDecimal;
        }
        for (PlanDrivageVO planOutputVO : planDrivageVOS) {
            System.out.println(planOutputVO.getDrivagePlanFootage());
            planOutput1 = planOutput1.add(planOutputVO.getDrivagePlanFootage());
        }
        return planOutput1;
    }

    /**
     * 计算掘进米
     *
     * @param executionFootageOutput
     * @return
     */
    private BigDecimal countYearRealFootage(ExecutionFootageOutputReq executionFootageOutput) {

        List<ExecutionFootageOutputVO> executionFootageOutputVOS = executionFootageOutputService.selectList(executionFootageOutput);


        if (executionFootageOutputVOS == null) {
            return BigDecimal.ZERO;
        }
        BigDecimal output = BigDecimal.ZERO;
        for (ExecutionFootageOutputVO executionFootageOutputVO : executionFootageOutputVOS) {
            BigDecimal footage = executionFootageOutputVO.getFootage();
            if (footage == null) {
                footage = BigDecimal.ZERO;
            }
            if (output == null) {
                output = BigDecimal.ZERO;
            }
            output = output.add(footage);

        }

        return output;
    }

    public String dateToday(Date date) {
        LocalDate now = LocalDate.now();

        int monthValue = now.getMonthValue();
        int year = now.getYear();
        if (monthValue < 10) {
            System.out.println(year + "0" + monthValue);
            return year + "0" + monthValue;

        }
        System.out.println(year + monthValue + "");
        return year + monthValue + "";

    }


    public int dateDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.roll(Calendar.DAY_OF_MONTH, -1);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        int day = Integer.parseInt(format.substring((format.lastIndexOf("-") + 1)));// 得今天是2022年10月13号，所以这个月的最大天数是 31
        return day;

    }

    /**
     * 获取上个月月份
     *
     * @return
     */
    private String getLastMonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        // 设置为当前时间
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        // 设置为上一个月
        //calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        date = calendar.getTime();
        return format.format(date);
    }

    /**
     * 获取本月计划产量
     */
    private BigDecimal getMonthcoalOutput(String mineCode,String companyCode) {
        Date date = new Date();
        QueryWrapper<PlanOutput> queryWrapper = new QueryWrapper();
        queryWrapper.eq("output_plan_name", "月计划" + dateToday(date)).eq(mineCode != null,"mine_code",mineCode).eq(companyCode != null,"company_code",companyCode);
        System.out.println("月计划" + dateToday(date));
        System.out.println(dateToday(date));
        List<PlanOutput> planOutputs = planOutputMapper.selectList(queryWrapper);

        BigDecimal planOutputbigDecimal = BigDecimal.ZERO;
        if (planOutputs == null || planOutputs.size() < 0) {
            return planOutputbigDecimal = BigDecimal.ZERO;
        }
        for (PlanOutput planOutput : planOutputs) {
            if (planOutput.getPlanOutput() == null) {
                planOutput.setPlanOutput(BigDecimal.ZERO);
            }
            planOutputbigDecimal = planOutputbigDecimal.add(planOutput.getPlanOutput());
        }
        return planOutputbigDecimal;
    }


    @Override
    public List<CoalWeekCount> selectListfootage(BaseReq baseReq) {
        QueryWrapper<CoalWeekCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "2").orderByDesc("sun_date");
        queryWrapper.ge(baseReq.getBeginDate() != null, "sun_date", baseReq.getBeginDate()).le(baseReq.getBeginDate() != null, "mon_date", baseReq.getEndDate());
        List<CoalWeekCount> list = this.list(queryWrapper);

        return list;
    }

    @Override
    public void calculatedWeeklyFootage(String mineCode,String companyCode) {
        Date date = new Date();
        int whichDay = date.getDay();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化一下
        Calendar calendar1 = Calendar.getInstance();//获取对日期操作的类对象
        Calendar calendar2 = Calendar.getInstance();//获取对日期操作的类对象
        Calendar calendar3 = Calendar.getInstance();//获取上周日时间
        Calendar calendar4 = Calendar.getInstance();//获取上周一时间


        calendar1.add(Calendar.DATE, -(whichDay - 1));
        Date montoday = calendar1.getTime();
        calendar2.add(Calendar.DATE, +(7 - whichDay));
        Date suntoday = calendar2.getTime();
        calendar3.add(Calendar.DATE, -(whichDay));
        Date lastsuntoday = calendar3.getTime();
        calendar4.add(Calendar.DATE, -(whichDay + 7));
        Date lastmontoday = calendar3.getTime();

        int dayDate = dateDay(date);
        PlanOutput planOutput = null;
        BigDecimal divide = null;
        LocalDate localDate = LocalDate.now();
        //当月最后一天
        LocalDate lastDay = localDate.with(TemporalAdjusters.lastDayOfMonth());
        //当月第一天
        LocalDate firstDay = localDate.with(TemporalAdjusters.firstDayOfMonth());
        WeekFields weekFields = WeekFields.ISO;
        LocalDate now = LocalDate.now();
        LocalDate mondayDate = now.with(weekFields.dayOfWeek(), 1L);//本周第一天
        LocalDate sundayDate = now.with(weekFields.dayOfWeek(), 7L);//本周最后一天
        QueryWrapper<CoalWeekCount> coalWeekCountQueryWrapper = new QueryWrapper<>();
        coalWeekCountQueryWrapper.eq("mon_date", mondayDate).eq("sun_date", sundayDate).eq("type", "2");
        if (mineCode !=null ){coalWeekCountQueryWrapper.eq("mine_code",mineCode);
        }
        if (mineCode == null){
            coalWeekCountQueryWrapper.isNull("mine_code");
        }
        CoalWeekCount one = this.getOne(coalWeekCountQueryWrapper);
        if (one == null) {

        }
        //上周一和周日
        LocalDate todayOfLastWeek = now.minusDays(7);
        LocalDate lastmonday = todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1);
        LocalDate lastsunday = todayOfLastWeek.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(1);

        boolean before = mondayDate.isBefore(firstDay);//本周第一天如果是本月第一天之前
        if (before) {
            //获取上个月的最后一天
            LocalDate lastMonthdate = LocalDate.now();
            lastMonthdate = lastMonthdate.minusMonths(1);
            LocalDate with = lastMonthdate.with(TemporalAdjusters.lastDayOfMonth());

            Period period = Period.between(mondayDate, with);
            int days = period.getDays() + 1;//相差多少天

            LocalDate lastDay1 = lastMonthdate.with(TemporalAdjusters.lastDayOfMonth());

            //当月第一天
            LocalDate firstDay1 = lastMonthdate.with(TemporalAdjusters.firstDayOfMonth());

            //在计算本月本周有多少天
            Period period1 = Period.between(firstDay, sundayDate);
            int days1 = period1.getDays() + 1;//相差多少天

            //查询上月的总计划/天数*本周上月所占天数+（本月总计划/本月天数*本周本月天数）
            String lastMonth = getLastMonth();
            //获取到上个月的计划进尺米数
            BigDecimal lastmonthcoalFootage = getMonthcoalFootage(lastMonth,mineCode);
            //获取本月的计划尺米数
            BigDecimal monthcoalFootage = getMonthcoalFootage(dateToday(date),mineCode);


            BigDecimal monthcoalmultiply = monthcoalFootage.divide(BigDecimal.valueOf(dayDate), 2, BigDecimal.ROUND_UP).multiply(BigDecimal.valueOf(days));
            BigDecimal monthcoalmultiply2 = lastmonthcoalFootage.divide(BigDecimal.valueOf(dayDate), 2, BigDecimal.ROUND_UP).multiply(BigDecimal.valueOf(days1));
            divide = monthcoalmultiply.add(monthcoalmultiply2);
        } else {
            //本月总计划/本月天数*本周本月天数=本周计划
            //本周推进度=本周第一天到本周最后一天累计回采长度
            //累计回采长度是这个工作面总共回采的长度
            //剩余长度= 这个工作面总长度-累计回采长度
            BigDecimal monthcoalOutput = getMonthcoalFootage(dateToday(new Date()),mineCode);
            divide = monthcoalOutput.divide(BigDecimal.valueOf(dayDate), 2, BigDecimal.ROUND_UP).multiply(BigDecimal.valueOf(7));
        }


        //获取年计划米数

        PlanDrivageReq planOutputReq = new PlanDrivageReq();
        int year1 = calendar1.get(Calendar.YEAR);
        //planOutputReq.setOutputPlanName(String.valueOf(year1));
        planOutputReq.setDrivagePlanName(String.valueOf(year1));
        if (mineCode != null){
            planOutputReq.setMineCode(mineCode);
        }
        BigDecimal yearFootMethod = getYearFootageMethod(planOutputReq);
//
        ExecutionFootageOutputReq finshexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        List<String> strings = new ArrayList<>();
        strings.add(year1 + "-01-01");
        strings.add(year1 + "-12-31");

        finshexecutionFootageOutputReq.setDateTimeRange(strings);
        if (mineCode != null){
            finshexecutionFootageOutputReq.setMineCode(mineCode);
        }
        //获取年实际完成
        BigDecimal finshCoaloutput = countYearRealFootage(finshexecutionFootageOutputReq);

        //本周完成量
        //BigDecimal cont = getWeekBigDecimal(montoday, suntoday);
        List<String> thisWeek = new ArrayList<>();
        thisWeek.add(String.valueOf(mondayDate));
        thisWeek.add(String.valueOf(sundayDate));
        ExecutionFootageOutputReq coutexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        coutexecutionFootageOutputReq.setDateTimeRange(thisWeek);
        if (mineCode != null){
            coutexecutionFootageOutputReq.setMineCode(mineCode);
        }
        BigDecimal cont = countYearRealFootage(coutexecutionFootageOutputReq);
        //上周完成量
        //BigDecimal lastcont = getWeekBigDecimal(lastmontoday, lastsuntoday);
        List<String> lastWeek = new ArrayList<>();
        lastWeek.add(String.valueOf(lastmonday));
        lastWeek.add(String.valueOf(lastsunday));
        ExecutionFootageOutputReq lastcoutexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        lastcoutexecutionFootageOutputReq.setDateTimeRange(lastWeek);
        if (mineCode != null){
            lastcoutexecutionFootageOutputReq.setMineCode(mineCode);
        }
        BigDecimal lastcont = countYearRealFootage(lastcoutexecutionFootageOutputReq);


        CoalWeekCount coalWeekCount = new CoalWeekCount();
        coalWeekCount.setMonDate(montoday);
        coalWeekCount.setSunDate(suntoday);
        //r日均
        BigDecimal divide1 = cont.divide(BigDecimal.valueOf(7), 2, BigDecimal.ROUND_UP);
        coalWeekCount.setDaily(divide1);
        //weekcoalOutput 本周完成量
        coalWeekCount.setLastWeekCoaloutput(cont);


        //BigDecimal decimalsetYearOutputRate = (finshCoaloutput.subtract(yearCoaloutputMethod)).divide(yearCoaloutputMethod, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
        coalWeekCount.setWeekOutputrate("--");
        if (lastcont != null && lastcont.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal weekdecimalsetYearOutputRate = (cont.subtract(lastcont)).divide(lastcont, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            coalWeekCount.setWeekOutputrate(weekdecimalsetYearOutputRate + "%");

        }
        //年完成百分比
        //coalWeekCount.setYearOutputRate(decimalsetYearOutputRate + "%");
        coalWeekCount.setScheduledPlan(yearFootMethod);


        //本年完成
        coalWeekCount.setYearFinshCoaloutput(finshCoaloutput);
        //年度计划
        coalWeekCount.setYearCoalOutput(finshCoaloutput);
        BigDecimal subtract = cont.subtract(lastcont);
        if (one != null) {
            coalWeekCount.setId(one.getId());
        }
        //周环比率

        //周环比量
        coalWeekCount.setWeekOutputConteRast(subtract);
        //上周工作量
        coalWeekCount.setLastWeekCoaloutput(lastcont);
        // 本周完成量
        coalWeekCount.setWeekcoalOutput(cont);
        //本周计划量
        coalWeekCount.setWeekplanOutput(divide);
        int lastyear = year1 - 1;

        List<String> lsatyearthisWeek = new ArrayList<>();
        lsatyearthisWeek.add(String.valueOf(mondayDate.minusYears(1)));
        lsatyearthisWeek.add(String.valueOf(sundayDate.minusYears(1)));
        ExecutionFootageOutputReq lastyearcoutexecutionFootageOutputReq = new ExecutionFootageOutputReq();
        BigDecimal lastyearcont = countYearRealFootage(lastyearcoutexecutionFootageOutputReq);

        coalWeekCount.setLastYearCoaloutput(lastyearcont);
        coalWeekCount.setType("2");
        //年完成百分比
        coalWeekCount.setYearOutputRate(  "--%");
        if (yearFootMethod.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal decimalsetYearOutputRate = (finshCoaloutput.subtract(yearFootMethod)).divide(yearFootMethod, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            coalWeekCount.setYearOutputRate(decimalsetYearOutputRate + "%");
        }

        BigDecimal onYear = cont.subtract(lastyearcont);
        if (lastyearcont.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal onYearRate = (cont.divide(lastyearcont, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100")));
            coalWeekCount.setOnYearRate(onYearRate + "%");
        }else {coalWeekCount.setOnYearRate( "--%");}
        //同比量
        coalWeekCount.setOnYear(onYear);
        //同比率


        //超欠
        BigDecimal backRreak = cont.subtract(divide);
        coalWeekCount.setBackBreak(backRreak);
        //超欠百分比
        if (divide.compareTo(BigDecimal.ZERO)!=0) {
            BigDecimal backBrakRate = backRreak.divide(divide, 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            coalWeekCount.setBackBreakRate(backBrakRate + "%");
        }else {
            coalWeekCount.setBackBreakRate( "--%");
        }
        coalWeekCount.setMineCode(mineCode);
        // int insert = coalWeekCountMapper.insert(coalWeekCount);
        //System.out.println(insert);
        boolean b = this.saveOrUpdate(coalWeekCount);
    }

    /**
     * 获取月掘进进尺米数
     *
     * @param lastMonth
     */
    private BigDecimal getMonthcoalFootage(String lastMonth ,String mineCode) {
        QueryWrapper<PlanDrivage> queryWrapper = new QueryWrapper();
        queryWrapper.eq("drivage_plan_name", "月计划" + lastMonth);
        if (mineCode != null){
            queryWrapper.eq("mine_code", mineCode);
        }
        List<PlanDrivage> planDrivages = planDrivageMapper.selectList(queryWrapper);
        BigDecimal drivagePlanFootage = BigDecimal.ZERO;
        if (planDrivages == null) {
            drivagePlanFootage = BigDecimal.ZERO;
        }
        for (PlanDrivage planDrivage : planDrivages) {
            if (planDrivage == null || planDrivage.getDrivagePlanFootage() == null) {
                planDrivage.setDrivagePlanFootage(BigDecimal.ZERO);
            }
            drivagePlanFootage = drivagePlanFootage.add(planDrivage.getDrivagePlanFootage());
        }
        return drivagePlanFootage;
    }


}







